from flask import Blueprint
from datetime import date

from zvms.models import User, UserNotice
from zvms.deco import *
from zvms.res import *
from zvms.util import *
import zvms.tokenlib as TK

user = Blueprint('user', __name__)

@user.route('/user/login', methods=['POST'])
@Deco
def login_NoToken(json_data, token_data):
    if json_data['version'] != CURRENT_VERSION:
        return error(CURRENT_VERSION_ERROR_MESSAGE)
    user = User.query.get_or_error(json_data['userid'], '用户名或密码错误')
    if user.password != json_data['password']:
        return error('用户名或密码错误')
    tmp = user.select('permission', userName='username', class_='class')
    tmp['classname'] = classIdToString(tmp['class'])
    return success('登录成功', token=TK.generateToken(user.select('permission', userId='userid', userName='username', class_='class')), **tmp)

@user.route('/user/logout', methods=['POST'])
@Deco
def logout(json_data, token_data):
    TK.remove(token_data)
    return success('登出成功')

@user.route('/user/info', methods=['POST'])
@Deco
def info(json_data, token_data):
    return success('获取成功', info=token_data)

@user.route('/user/getInfo/<int:userId>', methods=['POST'])
@Deco
def getInfo(userId, json_data, token_data):
    return success('获取成功', User.query.get_or_error(userId).select('userName', 'permission', class_='class'))

@user.route('/user/modPwd', methods=['POST'])
@Deco
def modifyPassword(json_data, token_data):
    user = User.query.get(token_data['userid'])
    if user.password != json_data['oldPwd']:
        return error('密码错误')
    user.password = json_data['newPwd']
    return success('修改成功')

@user.route('/user/notices')
@Deco
def getNotices(json_data, token_data):
    notices = User.query.get(token_data['userid']).notices
    if notices is None:
        return success('', data=[])
    notices = notices.split(',')
    data = []
    year, month, day = map(int, str(date.today()).split('-'))
    for i in notices:
        notice = UserNotice.query.get(i).select(noticeTitle='title', markdown='text', deadTime='deadtime')
        y, m, d = map(int, notice['deadtime'].split('-'))
        if y < year:
            continue
        elif y > year:
            data.append(notice)
        elif m < month:
            continue
        elif m > month:
            data.append(notice)
        elif d < day:
            continue
        else:
            data.append(notice)
    return success('', data=data)

@user.route('/user/sendNotice', methods=['POST'])
@Deco
def sendNotice(json_data, token_data):
    deadtime = json_data.get('deadtime', str(date.today()))
    id = str(UserNotice(
        noticeTitle=json_data['title'],
        noticeText=json_data['message'],
        deadTime=deadtime
    ).insert().noticeId)
    for i in json_data['target']:
        user = User.query.filter_by(class_=i).first()
        if user.notices is None:
            user.notices = id
        else:
            user.notices += ',' + id
    return success('发送成功')